<template>
  <div class="h-full flex flex-column">
    <div class="p-xl flex-between" style="border-bottom: 1px solid var(--el-border-color);">
      <h2 class="title">{{ isEdit ? '编辑 Moment' : '新增 Moment' }}</h2>
      <div class="flex gap-md">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">保存</el-button>
      </div>
    </div>

    <div class="p-xl" style="flex: 1; overflow-y: auto;">
      <el-form :model="form" label-width="80px" style="max-width: 800px;">
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="form.createdTime"
            type="datetime"
            placeholder="请选择创建时间（可选）"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="form.title" placeholder="请输入标题（可选）" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="15"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createMoment, getMomentDetail } from '../api'

const router = useRouter()
const route = useRoute()

const isEdit = ref(false)
const submitting = ref(false)

const form = ref({
  createdTime: '',
  title: '',
  content: ''
})

const goBack = () => {
  router.back()
}

const handleSubmit = async () => {
  if (!form.value.content.trim()) {
    ElMessage.warning('请输入内容')
    return
  }

  submitting.value = true
  try {
    await createMoment(form.value)
    ElMessage.success('保存成功')
    router.push('/moments')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    submitting.value = false
  }
}

onMounted(async () => {
  const id = route.params.id as string
  if (id) {
    isEdit.value = true
    try {
      const data = await getMomentDetail(id)
      form.value = {
        createdTime: data.createdTime,
        title: data.title,
        content: data.content
      }
    } catch (error) {
      console.error('获取详情失败:', error)
      ElMessage.error('获取详情失败')
    }
  }
})
</script>

<style scoped>
</style>
